//
//  ZYCHomeViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/7/29.
//

#import "ZYCHomeViewController.h"
#import "ZYCHomeRootHeaderView.h"
#import "ZYCHomeRootParentHeaderView.h"
#import "ZYCBannaerViewController.h"
#import "XLPageViewController.h"
#import "ZYCHomeNewsViewController.h"
#import "ZYCHomeBulletinViewController.h"
#import "ZYCWheelBannerModel.h"
#import "ZYCProtalNoticeListViewController.h"
#import "ZYCProtalCalendarViewController.h"
#import "ZYCManageDutyRecordViewController.h"
#import "ZYCManageTourRecordViewController.h"
#import "ZYCManageTourStatisticsViewController.h"
#import "ZYCTeachingAttendanceViewController.h"
#import "ZYCTeachingTeachLearningViewController.h"
#import "ZYCTeacherDiningViewController.h"
#import "ZYCStuLeaveRecordRootViewController.h"
#import "ZYCManageCourseRegistrationViewController.h"
#import "ZYCCommonBaseModel.h"
#import "ZYCUserLoginModel.h"
#import "NSString+File.h"
#import "ZYCApplianceRootModel.h"


@interface ZYCHomeViewController ()<UINavigationControllerDelegate,UIScrollViewDelegate,ZYCHomeRootHeaderViewDelegate,XLPageViewControllerDelegate,XLPageViewControllerDataSrouce,ZYCHomeRootParentHeaderViewDelegate>

@property (nonatomic, strong) UIScrollView * scrollView;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) XLPageViewController* pageViewController;
@property (nonatomic, strong) XLPageViewControllerConfig * config;
@property (nonatomic, strong) ZYCHomeRootHeaderView *headerView;
@property (nonatomic, strong) ZYCHomeRootParentHeaderView *parentHeaderView;
@property (nonatomic, strong) NSArray *titles;

@property (nonatomic, strong) NSString *roleType;
@property (nonatomic, strong) NSArray *authorityArray;

@end

@implementation ZYCHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.scrollView];
    self.titles = @[@"新闻",@"公告"];
    self.scrollView.contentInset = UIEdgeInsetsMake(-kStatusBarHeight-5, 0, 0, 0);
    self.scrollView.contentOffset = CGPointMake(0, kStatusBarHeight+5);

    [self loadBanner];
    NSInteger roleType =  [[NSUserDefaults standardUserDefaults] integerForKey:@"kUserRoleType"];
      if (roleType == 0) {//教师
          self.roleType = @"1";
          [self.scrollView addSubview:self.headerView];
          // 禁止滑动
          self.scrollView.contentSize = CGSizeMake(kScreenWidth, kScreenHeight + self.headerView.frame.size.height - kTabBarHeight - kStatusBarHeight);
          CGRect rect = self.view.bounds;
          rect.size.height = rect.size.height - kNavBarAndStatusBarHeight;
          rect.origin.y = self.headerView.frame.size.height;
          
          UIView *bgView = [[UIView alloc] init];
          bgView.frame = rect;
          
          CGRect pRect = rect;
          pRect.origin.y = 0;
          self.pageViewController.view.frame = pRect;
          self.pageViewController.view.layer.cornerRadius = 7.5;
          self.pageViewController.view.layer.masksToBounds = YES;
          self.pageViewController.delegate = self;
          self.pageViewController.dataSource = self;
          self.pageViewController.scrollEnabled = NO;
          [self addChildViewController:self.pageViewController];
          [self.scrollView addSubview:bgView];
          [bgView addSubview:self.pageViewController.view];

      }else{// 家长
          self.roleType = @"2";
          [self.scrollView addSubview:self.parentHeaderView];
          self.scrollView.contentSize = CGSizeMake(kScreenWidth, kScreenHeight + self.parentHeaderView.frame.size.height - kTabBarHeight - kStatusBarHeight);

          CGRect rect = self.view.bounds;
          rect.size.height = rect.size.height - kNavBarAndStatusBarHeight;
          rect.origin.y = self.parentHeaderView.frame.size.height;
          
          UIView *bgView = [[UIView alloc] init];
          bgView.frame = rect;
          
          CGRect pRect = rect;
          pRect.origin.y = 0;
          self.pageViewController.view.frame = pRect;
       
          self.pageViewController.view.layer.cornerRadius = 7.5;
          self.pageViewController.view.layer.masksToBounds = YES;
          self.pageViewController.delegate = self;
          self.pageViewController.dataSource = self;
          self.pageViewController.scrollEnabled = NO;
          [self addChildViewController:self.pageViewController];
          [self.scrollView addSubview:bgView];
          [bgView addSubview:self.pageViewController.view];
      }
    
    [self getUserInfo];
    [self querySemesterList];
    [self queryCourseList];

}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.delegate = self;
    NSInteger roleType =  [[NSUserDefaults standardUserDefaults] integerForKey:@"kUserRoleType"];
    if (roleType == 0) {//教师
        // 菜单权限
        [self getMenu];
    }
}
#pragma mark - UINavigationControllerDelegate
-(void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:[viewController isKindOfClass:[self class]] animated:YES];
}

#pragma mark - ZYCHomeRootHeaderViewDelegate

- (void)homeRootHeaderDidClickBanner:(ZYCWheelBannerModel *)model{
    if ([[self getCompleteWebsite:model.linkUrl] isUrlString]) {
        ZYCBannaerViewController *vc = [[ZYCBannaerViewController alloc] init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)tipShow{
    [MrjToast makeToast:@"暂无权限访问" makeView:self.view];
}
//通知
- (void)homeRootHeaderDidClickNotice:(NSString *)string{
    if ([self.authorityArray containsObject:string]) {
        ZYCProtalNoticeListViewController *vc = [[ZYCProtalNoticeListViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self tipShow];
    }

}
//周历
- (void)homeRootHeaderDidClickCalendar:(NSString *)string{
    if ([self.authorityArray containsObject:string]) {
        ZYCProtalCalendarViewController *vc = [ZYCProtalCalendarViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self tipShow];
    }
}
//值班记录
- (void)homeRootHeaderDidClickDutyRecord:(NSString *)string{
    if ([self.authorityArray containsObject:string]) {
        ZYCManageDutyRecordViewController *vc = [ZYCManageDutyRecordViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self tipShow];
    }

}
//巡堂记录
- (void)homeRootHeaderDidClickPatrolHallRecord:(NSString *)string{
    if ([self.authorityArray containsObject:string]) {
        ZYCManageTourRecordViewController *vc = [ZYCManageTourRecordViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self tipShow];
    }

}
//巡堂统计
- (void)homeRootHeaderDidClickPatrolHallStatistics:(NSString *)string{
    if ([self.authorityArray containsObject:string]) {
        ZYCManageTourStatisticsViewController *vc = [ZYCManageTourStatisticsViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self tipShow];
    }

}
//听评课
- (void)homeRootHeaderDidClickAttendance:(NSString *)string{
    if ([self.authorityArray containsObject:string]) {
        ZYCTeachingAttendanceViewController *vc = [ZYCTeachingAttendanceViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self tipShow];
    }

}
//评教评学
- (void)homeRootHeaderDidClickTeachingLearn:(NSString *)string{
    if ([self.authorityArray containsObject:string]) {
        ZYCTeachingTeachLearningViewController *vc = [ZYCTeachingTeachLearningViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self tipShow];
    }

}
//教师就餐
- (void)homeRootHeaderDidClickDineStatistics:(NSString *)string{
    if ([self.authorityArray containsObject:string]) {
        ZYCTeacherDiningViewController *vc = [ZYCTeacherDiningViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self tipShow];
    }

}

#pragma mark - ZYCHomeRootParentHeaderViewDelegate
- (void)homeRootParentHeaderDidClickBanner:(ZYCWheelBannerModel *)model{
    if ([[self getCompleteWebsite:model.linkUrl] isUrlString]) {
        ZYCBannaerViewController *vc = [[ZYCBannaerViewController alloc] init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
//通知
- (void)homeRootParentHeaderDidClickNotice{
    ZYCProtalNoticeListViewController *vc = [[ZYCProtalNoticeListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
//考勤记录
- (void)homeRootParentHeaderDidClickAttendanceRecord{
    ZYCManageCourseRegistrationViewController *vc = [ZYCManageCourseRegistrationViewController new];
    vc.enterType = ZYCCourseRegistrationEnterApplianceStuAttendance;//学生考勤
    [self.navigationController pushViewController:vc animated:YES];

}
//请假记录
- (void)homeRootParentHeaderDidClickLeaveRecord{
    ZYCStuLeaveRecordRootViewController *vc = [ZYCStuLeaveRecordRootViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}
//成长档案
- (void)homeRootParentHeaderDidClickCourseRegistration{
    ZYCManageCourseRegistrationViewController *vc = [ZYCManageCourseRegistrationViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma make - XLPageViewControllerDelegate
-(NSInteger) pageViewControllerNumberOfPage{
    return self.titles.count;
}

-(UIViewController *) pageViewController:(XLPageViewController *)pageViewController viewControllerForIndex:(NSInteger)index{
    if (index == 0) {
        ZYCHomeNewsViewController * vc = [[ZYCHomeNewsViewController alloc] init];
        return vc;
    }else if (index == 1) {
        ZYCHomeBulletinViewController * vc = [[ZYCHomeBulletinViewController alloc] init];
        return vc;
    }
    return nil;
}

-(NSString *) pageViewController:(XLPageViewController *)pageViewController titleForIndex:(NSInteger)index
{
    return self.titles[index];
}



#pragma mark - getters

- (NSArray *)authorityArray {
    if (!_authorityArray) {
        _authorityArray = [[NSArray alloc] init];
    }
    return _authorityArray;
}
-(UIScrollView *) scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kTabBarHeight)];
        _scrollView.delegate = self;
        _scrollView.bounces = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
    }
    return _scrollView;
}

- (ZYCHomeRootHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ZYCHomeRootHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 450)];
        _headerView.delegate = self;

    }
    return _headerView;
}
- (ZYCHomeRootParentHeaderView *)parentHeaderView {
    if (!_parentHeaderView) {
        _parentHeaderView = [[ZYCHomeRootParentHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 365)];
        _parentHeaderView.delegate = self;
        _parentHeaderView.backgroundColor = [UIColor clearColor];
    }
    return _parentHeaderView;
}


-(XLPageViewControllerConfig *) config{
    if (!_config) {
        _config = [XLPageViewControllerConfig defaultConfig];
        _config.titleViewAlignment = 100.f;
        _config.titleSpace = 0;
        _config.titleWidth = 40.0f;
        _config.titleViewHeight = 54.0f;
        _config.titleViewInset = UIEdgeInsetsMake(0, 20, 0, 20);
        _config.titleSelectedColor = HEX_RGB(kTitleMainColor);
        _config.titleSelectedFont = kSystemBoldFont(18.0f);
        _config.titleNormalFont = kSystemFont(13.0f);
        _config.titleNormalColor = HEX_RGB(kTitleLightGrayColor);
        _config.shadowLineHidden = YES;
        _config.separatorLineColor = HEX_RGB(@"#EFEFEF");
        _config.titleColorTransition = false;
    }
    return _config;
}


- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headerView.frame), kScreenWidth, kScreenHeight - kTabBarHeight - CGRectGetMaxY(self.headerView.frame))];
        _bgView.backgroundColor = [UIColor orangeColor];
    }
    return _bgView;
}
-(XLPageViewController *) pageViewController
{
    if (!_pageViewController) {
        _pageViewController = [[XLPageViewController alloc] initWithConfig:self.config];
    }
    return _pageViewController;
}

- (void)dealloc{
    self.navigationController.delegate = nil;
}

//获取课程列表
- (void)queryCourseList{
//    NSDictionary *params = @{
//        @"studentScope":@"0",
//    };
    [[URLManager sharedURLManager] getUrlString:Common_Get_QueryCourseList requestService:RequestServiceWorkBench parameters:nil progress:nil success:^(id  _Nullable responseObject) {
        if (SUCCESS(responseObject[@"code"])) {
            NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCCommonBaseModel class] json:responseObject[@"body"]];
            NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            NSString *path = [documentPath stringByAppendingPathComponent:@"course.data"];
            [NSKeyedArchiver archiveRootObject:array toFile:path];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//获取学期列表
- (void)querySemesterList{
    [[URLManager sharedURLManager] getUrlString:Common_Get_QuerySemesterList requestService:RequestServiceWorkBench parameters:nil progress:nil success:^(id  _Nullable responseObject) {
        if (SUCCESS(responseObject[@"code"])) {
            NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCCommonBaseModel class] json:responseObject[@"body"]];
            NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            NSString *path = [documentPath stringByAppendingPathComponent:@"semester.data"];
            [NSKeyedArchiver archiveRootObject:array toFile:path];
        }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

- (void)loadBanner{
    [[URLManager sharedURLManager] getUrlString:Home_Get_QueryPics requestService:RequestServiceWorkBench parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *wheelBanner = [NSArray yy_modelArrayWithClass:[ZYCWheelBannerModel class] json:responseObject[@"body"]];
                self.headerView.wheelBannerList = wheelBanner;
                self.parentHeaderView.wheelBannerList = wheelBanner;
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}
// 获取个人信息
- (void)getUserInfo{
    NSDictionary *params = @{
        @"roleType":self.roleType
    };
    [[URLManager sharedURLManager] postUrlString:Profile_Get_GetMyInfo requestService:RequestServiceSystem parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        if (SUCCESS(responseObject[@"code"])) {
            ZYCUserLoginModel *userLogin = [ZYCUserLoginModel yy_modelWithDictionary:responseObject[@"body"]];
            [userLogin saveUserLogin];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}


// 菜单栏
- (void)getMenu{
    NSDictionary *params = @{
        @"roleType":self.roleType
    };

    [[URLManager sharedURLManager] postUrlString:Profile_Post_Menu requestService:RequestServiceSystem parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        if (SUCCESS(responseObject[@"code"])) {
            NSArray *array = responseObject[@"body"];
            ZYCApplianceRootModel *appMenu = [ZYCApplianceRootModel yy_modelWithDictionary:array.lastObject];
            NSMutableArray *temp = [NSMutableArray arrayWithCapacity:0];
            for (ZYCApplianceRootModel *section in appMenu.children) {
                for (ZYCApplianceRootModel *model in section.children) {
                    if ([model.menuId isEqualToString:@"540759249913031"]) {//学生考勤
                        for (ZYCApplianceRootModel *m in model.children) {
                            [temp addObject:m.menuId];
                        }
                    }
                    if ([model.menuId isEqualToString:@"540759249913173"]) {//教师考勤
                        for (ZYCApplianceRootModel *m in model.children) {
                            [temp addObject:m.menuId];
                        }
                    }
                    [temp addObject:model.menuId];
                }
            }
            
            
            self.authorityArray = temp;
            NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            NSString *path = [documentPath stringByAppendingPathComponent:@"authority.data"];
         [NSKeyedArchiver archiveRootObject:self.authorityArray toFile:path];

        }else{
            [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}


- (NSString *)getCompleteWebsite:(NSString *)urlStr{
    NSString *returnUrlStr = nil;
    NSString *scheme = nil;
    assert(urlStr != nil);
    urlStr = [urlStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ( (urlStr != nil) && (urlStr.length != 0) ) {
        NSRange  urlRange = [urlStr rangeOfString:@"://"];
        if (urlRange.location == NSNotFound) {
            returnUrlStr = [NSString stringWithFormat:@"http://%@", urlStr];
        } else {
            scheme = [urlStr substringWithRange:NSMakeRange(0, urlRange.location)];
            assert(scheme != nil);
            if ( ([scheme compare:@"http"  options:NSCaseInsensitiveSearch] == NSOrderedSame)
                || ([scheme compare:@"https" options:NSCaseInsensitiveSearch] == NSOrderedSame) ) {
                returnUrlStr = urlStr;
            } else {
                //不支持的URL方案
            }
        }
    }
    return returnUrlStr;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
